package com.ophiux.wechat.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

import com.ophiux.wechat.model.OauthRequest;
import com.ophiux.wechat.servlet.RedirectServlet;
import com.ophiux.wechat.utils.CommonUtil;


/**
 * 微信网页授权获取用户信息执行器
 * @author chenh
 *
 */
public class OauthExecutor implements Executor<String> {

	
	private static Logger logger = LoggerFactory.getLogger(RedirectServlet.class);

	
	/**
	 * 网页授权获取openID URL地址
	 */
	private static String OAUTH_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
			"appid=APP_ID&secret=APP_SECRET&code=CODE&grant_type=authorization_code";
	
	/**
	 * 请求参数
	 */
	private OauthRequest oauthRequest;
	
	
	public OauthExecutor(OauthRequest _oauthRequest){
		this.oauthRequest = _oauthRequest;
	}
	
	@Override
	public String execute() {
		// TODO Auto-generated method stub
		String url = OAUTH_URL.replace("APP_ID",oauthRequest.getAppid())
				.replace("APP_SECRET", oauthRequest.getAppsecret())
				.replace("CODE", oauthRequest.getCode());
		logger.info("获取openId-URL:"+url);
		String tempValue="";
		String openId = "";
		String oauResp = "";
		try {
			 oauResp = CommonUtil.httpsRequest(url, CommonUtil.HTTP_GET, "");		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("微信授权结果:"+oauResp);
		JSONObject  jsonObj = JSONObject.fromObject(oauResp);
		if(jsonObj.containsKey("errcode")){
			//授权出错
			System.out.println(tempValue);
			openId = "";
		}else{
			openId = jsonObj.getString("openid");
		}
	
		return openId;
	}
	
	

}
